<?php

namespace app\mini\controller\dealer;

use app\common\controller\ApiController;
use app\common\exception\BaseException;
use app\common\model\DealerGoods;
use app\common\model\DealerGoodsBrand;
use app\common\model\DealerGoodsCate;
use app\common\model\DealerGoodsSpec;
use app\common\service\annotation\ControllerAnnotation;
use app\company\model\CompanyOrder;
use app\company\model\CompanyOrderDetail;
use app\company\model\CompanyPickOrder;
use app\company\model\DealerOrderDetail;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="仓库管理")
 */
class Warehouse extends ApiController
{
    /**
     * @var array|int|mixed
     */
    private mixed $board_type;

    /**
     * @throws BaseException
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        if($this->scene_id != 1){
            throw new BaseException(['message' => '场景不符！']);
        }
        $this->board_type = $this->request->get('type') ?? 1;
    }

    public function entrance(): Json
    {
        return match ($this->board_type) {
            '1' => $this->board(),
            '2' => $this->yj(),
            '3' => $this->stockDetail(),
            default => $this->error('类型参数错误'),
        };
    }

    /**
     * @return Json
     */
    private function board(): Json
    {
        $get = $this->request->get();
        // 处理时间
        $get['date'] = $get['date']??date("Y-m-d");
        $count = substr_count($get['date'],'-');
        switch ($count) {
            case 0:
                $startTime = strtotime(date($get['date'].'-1-1 00:00:00'));
                $endTime = strtotime(date(($get['date'] + 1).'-1-1 00:00:00'));
                break;
            case 1:
                $startTime = strtotime($get['date']);
                $endTime = strtotime($get['date'].'-1' . ' +1 month');
                break;
            case 2:
                $startTime = strtotime($get['date']);
                $endTime = $startTime + 86400;
                break;
            default:
                $startTime = strtotime(date('Y-m-d' ,time()).'00:00:00');
                $endTime = $startTime + 86400;
        }
        $where = [
            ['dealer_id','=',$this->uid],
            ['create_time', '>=', $startTime],
            ['create_time', '<', $endTime],
        ];
        $data = [];
//        $data['brand'] = (new DealerGoodsBrand())->where($where)->count();
        $data['brand'] = 0;
        $data['cate'] = (new DealerGoodsCate())->where($where)->count();
        $data['kw'] = 0;
        $data['goods'] = (new DealerGoods())->where($where)->count();
        $data['lq'] = 0;
        $data['gq'] = 0;
        $data['bs'] = 0;
        $data['dd'] = 0;
        $data['ck'] = [
            'order' => 1023,
            'num' => 10245,
            'money' => 0,
        ];
        $data['rk'] = [
            'order' => 279,
            'num' => 23517,
            'money' => 0,
        ];
        return $this->success($data);
    }

    private function yj(): Json
    {
        return $this->success();
    }

    private function stockDetail(): Json
    {
        $get = $this->request->get();
        $list = (new DealerGoods())->field('id,name,sales_stock,warehouse_stock')->where('dealer_id','=',$this->uid)->paginate($get['limit']??15)->each(function($vo){
//            $num = '';
//            $item->spec->each(function($spec) use (&$num){
//                $num .= $spec->stock.$spec->unit;
//            });
//            $item->num = $num;
            $this->dealStock($vo);
        });
        return $this->success($list);
    }

    public function dealStock($vo): void
    {
        $spec = json_decode($vo->spec()->select(), true);
        usort($spec, function ($a, $b) {
            return $b['ratio'] <=> $a['ratio'];  // 使用太空船操作符进行升序排序
        });
        $sales_str = $warehouse_str = '';
        $sales_stock = $old_sales_stock = $vo->sales_stock;
        $warehouse_stock = $old_warehouse_stock = $vo->warehouse_stock;
        $unit = '';
        foreach ($spec as $value){
            if(!$value['ratio']) continue;
            // 售卖库存
            $sales_quotient = intdiv($sales_stock, $value['ratio']);
            $sales_stock = $sales_stock % $value['ratio'];
            $sales_str .= $sales_quotient.$value['unit'];
            // 库内库存
            $warehouse_quotient = intdiv($warehouse_stock, $value['ratio']);
            $warehouse_stock = $warehouse_stock % $value['ratio'];
            $warehouse_str .= $warehouse_quotient.$value['unit'];
            if($value['unit_type'] == 1) $unit = $value['unit'];
        }
        $old_sales_stock = $old_sales_stock??0;
        $old_warehouse_stock = $old_warehouse_stock??0;
        $vo->num = $sales_str.' = '.$old_sales_stock.$unit;
        $vo->sales_stock = $sales_str.' = '.$old_sales_stock.$unit;
        $vo->warehouse_stock = $warehouse_str.' = '.$old_warehouse_stock.$unit;
    }

    public function outStock(): Json
    {
        $get = $this->request->get();
        $page = $get['page']??1;
        $limit = $get['limit']??10;
        $where = [];
        if(!empty($get['start_time']) && !empty($get['end_time'])) {
            $start = strtotime($get['start_time'].'00:00:00');
            $end = strtotime($get['end_time'].'23:59:59');
            $where[] = ['order.update_time','between',[$start,$end]];
        }
        $list = (new DealerGoods())->field('id,name')->where('dealer_id',$this->uid)->select()->each(function($vo)use($where){
            $detail = (new CompanyOrderDetail())->alias('detail')
                ->field('SUM(detail.num) num,detail.dealer_goods_id,detail.dealer_goods_spec_id,detail.update_time,spec.ratio,spec.unit')
                ->join('company_order order','order.id = detail.company_order_id')
                ->join('dealer_goods_spec spec','spec.id = detail.dealer_goods_spec_id')
                ->where('order.out_status',2)
                ->where('order.order_type',1)
                ->where('detail.dealer_goods_id',$vo['id'])
                ->where($where)->group('detail.dealer_goods_spec_id')->order('spec.ratio desc')->select();
            $numStr = '';
            $num = 0;
            foreach ($detail as $spec){
                $numStr .= $spec['num'].$spec['unit'];
                $num += $spec['num']*($spec['ratio']??0);
            }
            $unit = (new DealerGoodsSpec())->where('dealer_goods_id',$vo['id'])->where('unit_type',1)->value('unit');
            $numStr = $numStr ? $numStr .= ' = '.$num.$unit : '暂无';
            $vo->num = $numStr;
        });
        $list = array_filter($list->toArray(),function($item){
            return $item['num'] != '暂无';
        });
        $total = count($list);
        $data = array_slice($list, ($page - 1) * $limit, $limit);
//        halt($list);
        // 别删，说不定还得改回去！
//        $list = (new CompanyOrderDetail())->alias('detail')
//            ->field('detail.id,detail.num,detail.dealer_goods_id,goods.id,goods.name,detail.create_time')
//            ->join('company_order order','order.id = detail.company_order_id')
//            ->join('dealer_goods goods','goods.id = detail.dealer_goods_id')
//            ->where('order.dealer_id',$this->uid)
//            ->where('order.out_status',2)
//            ->where($where)
//            ->order('detail.create_time desc')
//            ->paginate($get['limit']??15);

        return $this->success(compact('data','total'));
    }

    public function inStock(): Json
    {
        $get = $this->request->get();
        $page = $get['page']??1;
        $limit = $get['limit']??10;
        $where = [];
        if(!empty($get['start_time']) && !empty($get['end_time'])) {
            $start = strtotime($get['start_time'].'00:00:00');
            $end = strtotime($get['end_time'].'23:59:59');
            $where[] = ['order.update_time','between',[$start,$end]];
        }
        $list = (new DealerGoods())->field('id,name')->where('dealer_id',$this->uid)->select()->each(function($vo)use($where){
            $detail = (new DealerOrderDetail())->alias('detail')
                ->field('SUM(detail.num) num,detail.dealer_goods_id,detail.dealer_goods_spec_id,detail.update_time,spec.ratio,spec.unit')
                ->join('dealer_order order','order.id = detail.dealer_order_id')
                ->join('dealer_goods_spec spec','spec.id = detail.dealer_goods_spec_id')
                ->where('order.order_status',3)
                ->where('detail.order_type',1)
                ->where('detail.dealer_goods_id',$vo['id'])
                ->where($where)->group('detail.dealer_goods_spec_id')->order('spec.ratio desc')->select();
            $numStr = '';
            $num = 0;
//            if($vo['id'] == 585) halt($detail->toArray());
            foreach ($detail as $spec){
                $numStr .= $spec['num'].$spec['unit'];
                $num += $spec['num']*($spec['ratio']??0);
            }
            $unit = (new DealerGoodsSpec())->where('dealer_goods_id',$vo['id'])->where('unit_type',1)->value('unit');
            $numStr = $numStr ? $numStr .= ' = '.$num.$unit : '暂无';
            $vo->num = $numStr;
        });
        $list = array_filter($list->toArray(),function($item){
            return $item['num'] != '暂无';
        });
        $total = count($list);
        $data = array_slice($list, ($page - 1) * $limit, $limit);
//        halt($list);
        // 别删，说不定还得改回去！
//        $list = (new DealerOrderDetail())->alias('detail')
//            ->field('detail.id,detail.num,detail.dealer_goods_id,goods.id,goods.name,detail.create_time')
//            ->join('dealer_order order','order.id = detail.dealer_order_id')
//            ->join('dealer_goods goods','goods.id = detail.dealer_goods_id')
//            ->where('order.dealer_id',$this->uid)
//            ->where('order.order_status',3)
//            ->where($where)
//            ->order('detail.create_time desc')
//            ->paginate($get['limit']??15);

        return $this->success(compact('data','total'));
    }
}